define(function(require, exports, module){
	var pubjs = require('pubjs');
	var $ = require("jquery");
	var util = require('util');
	var view  = require('@base/view');

	var Base = view.container.extend({
		init: function(config){
			this.$defaultName = LANG('新建广告监测_') + util.date('YmdHis');
			config = pubjs.conf(config,{
				'class': 'P-monitorBasic',
				'tplFile': '/tpl/monitor/editStep/basic.tpl',
				'url': {
					'addSubChannel': 'adSubChannel/add'
				},
				"vModel": {
					'isAddChannel': false,
					'evSelectAdBtnClick': this.eventSelectAdBtnClick.bind(this)
				}
			})
			this.$adPositions = [];
			this.Super('init', arguments);
		},
		afterBuild: function(){
			var config = {
				'monitorName': {
					'placeholder': "不超过50个字符",
					'width': 300,
					'value': this.$defaultName,
				},
				'addChannel': {
					'value': LANG('新建渠道'),
					'class': 'btn btn-default ml20',
					'width': 100
				},
				'addSpot': {
					'value': LANG('添加广告位'),
					'class': 'btn btn-default mt10',
					'width': 100
				},
				'adList': {
					'cols':[
						{type:'id', width:80},
						{name:'MassMediaName', text:LANG('媒体'), align:'left'},
						{name:'Name', text: LANG('广告位名称'),align:'left'},
						{type:'op', width:50, html:'<a href="#" data-op="remove">'+LANG('删除')+'</a>'}
					],
					'url': "spot/monitorList",
					'reqType': "websocket",
					'opClick': true,
					'default_sort': false,
					'emptyText': LANG('请选择添加广告位'),
					'hasExport': false,
					'hasAmount': false,
					'auto_load': false,
					'hasPager': false,
					'hasTab': false,
					'hasSearch': false,
					'eventDataLoad': true
				},
				'planDrop': {
					'width': 300,
					'url': 'plan/list',
					'reqType': 'websocket',
					'all': true,
					'param': {
						'noAmount': true,
						'mongoField': ['Name'],
						'no_limit': true,
						'no_default_plan': true
					},
					'def': LANG('请选择计划'),
					'name': 'Name',
					'key': '_id',
					'panel_config': {
						'hasSearch': true,
						'height': 200
					}
				},
				'channelDrop':{
					'width': 300,
					'def': LANG('请选择渠道'),
					'url': 'adSubChannel/list',
					'reqType': 'websocket',
					'option_height': 300,
					'key': 'id',
					'name': 'name'
				},
				'channelName':{
					'width': 200
				},
				'saveChannel': {
					'width': 60,
					'value': LANG('保存'),
					'class': "btn btn-confirm"
				},
				'cancelChannel': {
					'width': 60,
					'value': LANG('取消'),
					'class': "btn btn-default"
				},
				'startTime': {
					'min': util.date('Y-m-d',util.today()),
					'value': util.date('Y-m-d',util.today())
				},
				'endTime':{
					'min': util.date('Y-m-d',util.today())
				},
				'tag':{
					'tips': LANG('给广告监测贴上标签，方便管理。多个标签用“,”分开。'),
					'hasLabel': false,
					'label': LANG('标签：'),
					'reqType': 'websocket',
					'async': true,
					'database': 'campaign/labels',
				}
			}
			this.buildFromTemplate(config);
		},
		onInputClick: function(ev){
			switch (ev.name){
			 	case "addSpot":
			 		this.eventSelectAdBtnClick();
			 		break;
			 	case "addChannel":
			 		this.showChannel();
			 		break;
			 	case "cancelChannel":
			 		this.hideChannel();
			 		break;
			 	case "saveChannel":
			 		this.saveChannel();
			 }
		},
		showChannel: function(){
			this.vm.$.isAddChannel = !this.vm.$.isAddChannel;
		},
		hideChannel: function(){
			this.vm.$.isAddChannel = false;
		},
		saveChannel: function(){
			var self = this;
			var c = this.getConfig();
			//保存渠道并更新下拉菜单
			var name = this.$.channelName.getValue();
			if(name.length === 0){
				pubjs.alert("请输入渠道名称");
				return false;
			}
			pubjs.mc.send(c.url.addSubChannel,{
				Name: name
			},function(err,data){
				if(err){
					pubjs.error(err);
					pubjs.alert(err.message);
					return false;
				}
				self.$.channelDrop.load();
				self.hideChannel();
			});
		},
		reset: function(){
			this.$.monitorName.reset();
			this.$.adList.reset();
			this.$.planDrop.reset().enable();
			this.$.channelDrop.reset();
			this.$.tag.reset();
			this.$.monitorName.setValue(this.$defaultName);
			this.$.startTime.setData(util.date('Y-m-d',util.today()));
			this.$.adList.setData([]);
			this.$.adList.setParam({
				"ids": []
			});
			this.$.selectAd.reset();
			this.$adPositions = [];

			return this;
		},
		getData: function(){
			var mod = this.$;
			var data = {};

			data.PlanId = +mod.planDrop.getValue().id;
			data.Name = mod.monitorName.getValue();
			data.StartTime = mod.startTime.getData();
			data.EndTime = mod.endTime.getData();
			data.AdxId = +mod.channelDrop.getData();
			data.SpotIds = [];
			util.each(this.$adPositions,function(value){
				data.SpotIds.push(value._id);
			});
			data.Label = this.$.tag.getData();
			return(data);
		},
		setData: function(data){
			var mod = this.$;
			mod.planDrop.setValue(data.PlanId).disable();
			mod.monitorName.setValue(data.Name);
			mod.startTime.setData(data.StartTime);
			mod.endTime.setData(data.EndTime);
			mod.channelDrop.setData(data.Agent.AdxId);
			if(data.Agent.SpotIds||data.Agent.SpotIds.length !== 0){
				mod.adList.setParam({
					"ids": data.Agent.SpotIds
				},true).load();
			}
			mod.tag.setData(data.Label);
		},
		validate: function(){
			var name = this.$.monitorName.getValue();
			if(!this.$.planDrop.getValue()){
				pubjs.alert("请先选择计划");
				return false;
			}
			if(name.length > 50 || name.length == 0){
				pubjs.alert("监测名称应在0-50字符之间");
				return false;
			}
			if(!this.$.adList.getData()){
				pubjs.alert("请先选择广告位");
				return false;
			}
			return true;
		},
		// 选择广告位消息
		onSelectAdPosition: function(ev) {
			var data = [];
			util.each(ev.param, function(item) {
				data.push(item);
			});
			this.$adPositions = data;
			this.$.adList.setData(data);
			return false;
		},
		//已选广告位表格回调，设置$adPositions
		onGridDataLoad: function(ev){
			this.$adPositions = ev.param.items;
		},
		// 移除广告位记录
		onListOpClick: function(ev) {
			if (ev.source === this.$.adList && ev.param.op === 'remove') {
				this.removeAdPosition(ev.param.data);
				return false;
			}
		},
		removeAdPosition: function(position) {
			var id = position;

			if (position && position._id) {
				id = position._id;
			}
			util.remove(this.$adPositions, position._id, '_id');
			this.$.adList.setData(this.$adPositions);
		},
		// 切换不同渠道时的事件
		onOptionChange: function(ev){
			var self = this;
			var param = ev.param;
			switch (ev.name){
				case 'channelDrop':
					if (self.$adPositions.length > 0){
						pubjs.confirm(LANG('切换渠道, 将会丢失当前广告位设置信息. 要确认切换吗?'), function(res) {
							if (res) {
								self.emptyAdPosition();
							} else {
								self.$.channelDrop.setData(param.last);
							}
						});
					}
					break;
				case "planDrop":

					break;
			}

			return false;
		},
		// 清空广告位信息
		emptyAdPosition: function() {
			var self = this;
			self.$adPositions = [];
			self.$.adList.setData([]);
			self.$.selectAd.reset().setValue([]);
		},
		// 选择广告位按钮事件
		eventSelectAdBtnClick: function() {
			var adType;
			var channelData = this.$.channelDrop.getData(true) || {};
			var channelId = channelData.id;
			var channelName = channelData.name;

			if (!channelId) {
				return pubjs.alert(LANG('请先选择渠道'));
			}

			this.$.selectAd.setValue(this.$adPositions).reset().setParam({
				// AdShowTypeEx: +adType,
				ChannelId: channelId,
				// XXX: 新建时需要传入渠道名称以显示
				ChannelName: channelName
			}).load().show();

			this.cast('setChannelId', channelId);
		}
	});

	exports.base = Base;
});